#!/usr/bin/python
# generateScripts 

'''
Created on July 7, 2011

This modules is used in for ATLAS Tier 3g cluster confgiuration
using Virtual Machines and Puppet (http://www.puppetlabs.com). 


Followw these steps to create the kickstart and other necessary files for your ATLAS
Tier 3g cluster

1) Create the configuration files for your cluster

   ./generateScripts xxx # where 'xxx' is the name of your configuration

   If the directory ./xxx, where 'xxx' is your configuration name, does not
   exist then the configuration templates and other necessary files will be
   copied to that directory for you to edit.

  * Basic Configuration: Customize parameters.py mentioned in the output of the previous action

       vi ./xxx/src/parameters.py # where 'xxx' is the name of your configuration

  * Kickstart files: Customize the kickstart templates mentioned in the output of the previous action

       vi ./xxx/templates/ks_yyy.cfg.template # where 'xxx' is the name of your configuration
                                              # kickstart-xxx.cfg where 'xxx' is the node name.
2) Generate all kickstart files and other necessary files. 

   ./generateScripts my-cfg
   ls ./my-cfg # you should see all the generated kickstart
               # files kickstart-xxx.cfg where 'xxx' is the node name.
                                                                                   
Functions

importAllModule - dynamically imports * from the specified module
setup - setup the AT3Cfg with the parameters
__main__ - the main program

@author: yyao@lbl.gov, vchendrix@lbl.gov
'''

import os
import shutil
import sys
sys.path.insert(0, './src')
from at3cfg import *
from optparse import OptionParser


def importAllModule(moduleName):
    """
       Dynamically imports all classes, variables and functions from 
       the nameed module
    """
    module = __import__(moduleName,globals(),locals())
    for k in dir(module):
            globals()[k] = module.__dict__[k]


def setup(cfg,pwdBootloader,pwdRoot,pwdLdapRoot,pwdCondor,timeZone,linuxInstallUrl,privateSubnet,domainName,numWorkers,nfs,head,interactive,pxyCacheSize,pxyEmail,pxyCacheMem):
    ''' Setup the At3Cfg 
        
        cfg - at3cfg.AT3Cfg to configure
        pwdBootLoader - the password for the boot loader
        pwdLdapRoot - the ldap root password
        pwdCondor - the condor master password
        timeZone - the timeZone
        linuxInstallUrl - the distribution URL for linux to be installed
        privateSubnet - the private subnet (i.e. 198.168.100)
        domainName - the domain name of your cluster ( i.e. myschool.edu )
        numWorkers - the number of workers
        nfs - dictionary defined for use as the NFS node
        head - dictionary defined for use as the head node
        interactive - list of dictionaries define as interactive nodes  
        pxyCacheSize - the proxy cache size
        pxyEmail - the proxy email address
        pxyCacheMem - the proxy cache memory
    
    
    '''

    PRIVATE_NFS_CLIENTS = "%s.0/255.255.255.0" % privateSubnet
    

    cfg.set("BOOTLOADERPASS",pwdBootloader)
    cfg.set("ROOTPW",pwdRoot)
    cfg.set("TIMEZONE",timeZone)
    cfg.set("URL",linuxInstallUrl)
    cfg.set("DOMAINNAME",domainName)
    cfg.set("CLUSTERNAME","Tier3 at %s" % domainName)
    cfg.set("NFSCLIENTLIST",PRIVATE_NFS_CLIENTS)
    cfg.set("PRIVATESUBNETPREFIX",PRIVATE_SUBNET_PREFIX)

    #LDAP
    dc = domainName.split('.')
    ldapSuffix =''
    for i in range(len(dc)):
        ldapSuffix += "dc=%s" % dc[i]
        if (i + 1) < len(dc):
            ldapSuffix += ','
    cfg.set("LDAPSUFFIX",ldapSuffix)
    cfg.set("LDAPROOTPW",pwdLdapRoot)

    #Proxy
    cfg.set("PROXYCACHESIZE",pxyCacheSize)
    cfg.set("PROXYEMAIL",pxyEmail)
    cfg.set("PROXYCACHEMEM",pxyCacheMem)
    pxyName = "Proxy"
    for i in range(len(dc)):
        pxyName += dc[i].title()
    cfg.set("PROXYNAME",pxyName)

    #Condor
    cndrFSDomain = ""
    for i in range(len(dc)):
        cndrFSDomain += dc[i].title()
    cndrFSDomain += "Tier3"
    cfg.set("CONDORFILESYSTEMDOMAIN",cndrFSDomain)
    cfg.set("CONDORPASSWORD",pwdCondor)

    # NODES
    cfg.setServiceNode_2Nic(role=nfs['role'], hostname=nfs['hostname'],
            publicip=nfs['publicip'],netmask=nfs['netmask'],gateway=nfs['gateway'],dns=nfs['dns'],overwrite=nfs['overwrite'])
    cfg.setServiceNode_2Nic(role=head['role'],hostname=head['hostname'],
            publicip=head['publicip'],netmask=head['netmask'],overwrite=head['overwrite'])
    cfg.setServiceNode_1Nic(role="LDAP", hostname=LDAP_HOSTNAME, overwrite=True)
    cfg.setServiceNode_1Nic(role="PROXY",hostname=PROXY_HOSTNAME,overwrite=True)

    for n in interactive:
        cfg.addInteractiveNode(hostname=n['hostname'],publicip=n['publicip'],netmask=n['netmask'])

    for i in range(1,numWorkers+1):
        workername="worker%03d"%i
        cfg.addWorkerNode(hostname=workername)


if __name__ == '__main__':
    """
        Python Main function
    """
     
    # Parse the command line for options and arguments
    parser = OptionParser(description="This modules is used in for ATLAS Tier 3g cluster confgiuration using Virtual Machines and Puppet (https://twiki.cern.ch/twiki/bin/viewauth/Atlas/VMPuppetAssistedTier3Install).  ",usage="usage: %prog [options]", version="%prog 1.0")
    parser.add_option("-n", "--name",
                   dest="config_name",
                   default="mytier3",
                   help="The name of the ATLAS T3g configuration. This will be the name of the destination directory for the configuration.  Default value is 'mytier3'") 
    (options, args) = parser.parse_args() 
    
    # Now we ned need to get our options and use them
    print options
    name = options.config_name

    # Create the directories to be copied
    cfgDir = "./%s" % name
    templatesDir = "%s/templates" % cfgDir
    paramsPy = "%s/src/parameters.py" % cfgDir 
    
    if not os.path.exists(cfgDir):
        # The parameters file had not been created. Copy all of the
        # templates and parameters for the specified configuration name
        try:
            shutil.copytree('./resources/',cfgDir)
        except:
            print "Unexpected error:", sys.exc_info()[0]

        # add the src directory in the cfgDir to the python path
        sys.path.insert(0, '%s/src' % cfgDir)

        # load the parameters module and import *
        importAllModule('parameters')


        print "Creating %s configuration files" % name
        print "\tCustomize your kickstart setup parameters in %s" % paramsPy
        print "\tCustomize your templates in %s" % templatesDir

    else:
        ## Yes Parameters have been configured 
        # add the src directory in the cfgDir to the python path
        sys.path.insert(0, '%s/src' % cfgDir)

        # load the parameters module and import *
        importAllModule('parameters')

        # Configure the Tier 3 Cluster
        cfg=AT3Cfg(name=name,**PRIVATE_NETWORKING)

        setup(cfg,**CONFIG_PARAMETERS)

        # Now, Generate all configuration files
        # from the tempalates
        AT3_GenerateAllKS(cfg)
        AT3_GenerateEtcHosts(cfg)

        AT3_GenerateVMCreationScripts(cfg)
        AT3_GeneratePXELinuxCFG(cfg)

        AT3_GenerateNodesPP(cfg)
        print "\n\nAll of your configuration files are in %s" % cfgDir
